#pragma once 

#include <string>
#include <jsoncpp/json/json.h>

//定制协议的过程,目前就是定制结构化数据的过程
//请求格式
//我们自己定义的协议, client和server都必须遵守,这个就是自定义协议
typedef struct request
{
  int left;
  int right;
  char op;
}request_t;

//响应格式
typedef struct response
{
  //server运算完毕的计算状态
  int code;
  //计算结果,可以区分是正常的计算结果,还是异常的计算结果
  int result;
}response_t;

//request_t -> string 
 std::string serialize_request(const request_t &req)
{
    Json::Value root;
    root["data_left"] = req.left;
    root["data_right"] = req.right;
    root["operator"] = req.op;

    Json::FastWriter writer;
    std::string json_string = writer.write(root);
    return json_string;
}

//string -> request_t
request_t deserialize_request(const std::string& json_string)
{
    request_t req;
    
    Json::Reader reader;
    Json::Value root;

    reader.parse(json_string, root);
    req.left = root["data_left"].asInt();
    req.right = root["data_right"].asInt();
    req.op = (char)root["operator"].asInt();

    return req;
}

//response_t -> string 
std::string serialize_response(const response_t& resp)
{
    Json::Value root;
    root["code"] = resp.code;
    root["result"] = resp.result;

    Json::FastWriter writer;
    std::string res = writer.write(root);

    return res;
}

//string -> response_t
response_t deserialize_response(const std::string& json_string)
{
    response_t resp;

    Json::Reader reader;
    Json::Value root;
    
    reader.parse(json_string, root);
    resp.code = root["code"].asInt();
    resp.result = root["result"].asInt();

    return resp;
}
